import { createRouter, createWebHistory } from 'vue-router'
import Login from './auth/Login.vue'
import Dashboard from './views/Dashboard.vue'
import Home from './dashboard/Home.vue'
import FamilyMemberList from './family/FamilyMemberList.vue'
import FamilyMemberDetail from './family/FamilyMemberDetail.vue'
import FamilyTreeVisualization from './family/FamilyTreeVisualization.vue'
import FamilyMemberMap from './family/FamilyMemberMap.vue'
import UserPermissionManagement from './user/UserPermissionManagement.vue'

// 创建路由
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true }
      },
      {
        path: '/family-members',
        name: 'FamilyMemberList',
        component: FamilyMemberList,
        meta: { requiresAuth: true }
      },
      {
        path: '/family-members/new',
        name: 'FamilyMemberCreate',
        component: FamilyMemberDetail,
        meta: { requiresAuth: true }
      },
      {
        path: '/family-members/:id',
        name: 'FamilyMemberEdit',
        component: FamilyMemberDetail,
        meta: { requiresAuth: true },
        props: true
      },
      {
        path: '/family-tree-visualization',
        name: 'FamilyTreeVisualization',
        component: FamilyTreeVisualization,
        meta: { requiresAuth: true }
      },
      {
        path: '/family-member-map',
        name: 'FamilyMemberMap',
        component: FamilyMemberMap,
        meta: { requiresAuth: true }
      },
      {
        path: '/user-permission-management',
        name: 'UserPermissionManagement',
        component: UserPermissionManagement,
        meta: { requiresAuth: true }
      }
    ]
  }
]

// 创建路由器实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 获取存储的token
    const token = localStorage.getItem('satoken')
    
    // 如果没有token，重定向到登录页
    if (!token) {
      next('/login')
    } else {
      // 如果有token，继续导航
      next()
    }
  } else {
    // 不需要认证的页面，直接访问
    next()
  }
})

export default router